package com.atguigu.ggkt.user.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.ggkt.model.user.UserInfo;
import com.atguigu.ggkt.user.service.UserInfoService;
import com.atguigu.ggkt.utils.JwtHelper;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;

@Controller //*需要页面跳转。restcontroll只是返回数据
@RequestMapping("/api/user/wechat")
public class WechatController {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private WxMpService wxMpService;

    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;

    //授权跳转
    @GetMapping("authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl,
                            HttpServletRequest request) {
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl
                (userInfoUrl,
                        WxConsts.OAUTH2_SCOPE_USER_INFO,
                        //对应前端的替换3
                        URLEncoder.encode(returnUrl.replace("guiguketan", "#")));
        return "redirect:" + redirectURL;
    }

    //对应前端的userInfo方法
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        //code请求
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        //获取openid
        String openId = wxMpOAuth2AccessToken.getOpenId();
        System.out.println("opid=" + openId);
        //微信用户信息
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        System.out.println("wxMpUser" + JSON.toJSONString(wxMpUser));

        //查数据库
        UserInfo userInfo = userInfoService.getUserInfoByOpenId(openId);
        //如果数据库查不到：
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setOpenId(openId);
            userInfo.setUnionId(wxMpUser.getUnionId());
            userInfo.setNickName(wxMpUser.getNickname());
            userInfo.setAvatar(wxMpUser.getHeadImgUrl());
            userInfo.setSex(wxMpUser.getSexId());
            userInfo.setProvince(wxMpUser.getProvince());
            userInfoService.save(userInfo);
        }

        //通过token值，进行跳转【通过jwt生成】
        String token = JwtHelper.createToken(userInfo.getId(),userInfo.getNickName());

        //token是参数：& token不是参数：?
        if (returnUrl.indexOf("?")==-1){
            return "redirect:"+returnUrl+"?token="+token;
        }else{
            return "redirect:"+returnUrl+"&token="+token;
        }
    }

}

